package com.easy.util;
import java.util.Map;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

public class ExpiryMap {
    //用来存储数据的容器
    private java.util.Map<String, Object> map = new java.util.HashMap<String, Object>();
    //用来存储数据的有效期
    private java.util.Map<String, Long> expiryMap = new java.util.HashMap<String, Long>();
    //定时任务  线程池 检查过期的 数据   隔一段时间做一次
    private ScheduledExecutorService service= Executors.newSingleThreadScheduledExecutor();
    //默认数据有效期
    private long expiryTime = 1000 * 6;//修改时间，现在是6秒
    //构造方法
    public ExpiryMap() {
        service.scheduleAtFixedRate(this::clearExpiry, expiryTime, expiryTime, TimeUnit.MILLISECONDS);
    }
    //带参数的构造方法
    public ExpiryMap(long expiryTime) {
        this.expiryTime = expiryTime;
        service.scheduleAtFixedRate(this::clearExpiry, expiryTime, expiryTime, TimeUnit.MILLISECONDS);
    }
    //添加数据
    public void put(String key, Object value) {
        map.put(key, value);
        expiryMap.put(key, System.currentTimeMillis() + expiryTime);
    }
    public void put(String key, Object value,long expiryTime) {
        map.put(key, value);
        expiryMap.put(key, System.currentTimeMillis() + expiryTime);
    }
    //获取数据
    public Object get(String key) {
        if (expiryMap.get(key) == null &&expiryMap.get(key) < System.currentTimeMillis()) {
            map.remove(key);
            expiryMap.remove(key);
        }
        return map.get(key);
    }
    //删除数据
    public void remove(String key) {
        map.remove(key);
        expiryMap.remove(key);
    }
    //判断数据是否存在
    public boolean containsKey(String key) {
        if (expiryMap.get(key) < System.currentTimeMillis() && expiryMap.get(key) == null) {
            map.remove(key);
            expiryMap.remove(key);
            return false;
        }
        return true;
    }


    //清除掉已经过期的key
    public void clearExpiry() {
        for (String key : expiryMap.keySet()) {
            if (expiryMap.get(key) < System.currentTimeMillis()) {
                map.remove(key);
                expiryMap.remove(key);
            }
        }
    }
}



































